/*  
* Copyright (c) 2010, James Daniello
* This project is licensed under the 'New BSD' license.
* The full text of the license can be found in the root
* directory under the filename "LICENSE"
*/

package src.engine;

import org.keplerproject.luajava.LuaState;
import org.keplerproject.luajava.LuaStateFactory;

/**
* This class is the PICAIU class for LuaJava scripts. Here they can be created and asked to call
* their functions.
*/
public class PICAIULuaScript{

  private LuaState luaState;
  private boolean loaded = false;
  
  /**
  * Creates a new LuaState given a script string. Note, it doesn't accept the name of a .lua file,
  * rather it takes the script in string format.
  */
  public PICAIULuaScript(String script){
    try{
    luaState = LuaStateFactory.newLuaState();
    luaState.openLibs();
    luaState.LdoString(script);
    //luaState.LloadString(script);
    loaded = true;
    }catch(Exception e){
      System.out.println("Could not load scipt file: \""+script+"\"");
    }
  }
  
  /**
  * Closes this LuaScript
  */
  public void close(){
    luaState.close();
  }
  
  /**
  * Runs the given function in the Lua file, passing object as the Java object to act on
  */
  public void runFunction(String function, Object object){
    if(loaded){
      luaState.getGlobal(function);
      luaState.pushJavaObject(object);
      luaState.pcall(1,0,0);
    }
  }
  /**
  * Runs the given function in the Lua file, passing object as the Java object to act on
  */
  public void runFunction(String function, Object object, Object object2){
    if(loaded){
      luaState.getGlobal(function);
      luaState.pushJavaObject(object);
      luaState.pushJavaObject(object2);
      luaState.pcall(2,0,0);
    }
  }
  
}